package com.meeting.order.service.impl;

import com.meeting.order.domain.Meeting;
import com.meeting.order.domain.MeetingRoom;
import com.meeting.order.dto.RoomStatusDTO;
import com.meeting.order.mapper.MeetingMapper;
import com.meeting.order.mapper.MeetingRoomMapper;
import com.meeting.order.service.MeetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MeetingServiceImpl implements MeetingService {
    
    @Autowired
    private MeetingMapper meetingMapper;
    
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Meeting addBooking(Meeting meeting) {
        // 参数校验
        if (meeting == null) {
            throw new RuntimeException("会议信息不能为空");
        }
        
        if (!StringUtils.hasText(meeting.getRoomId())) {
            throw new RuntimeException("会议室ID不能为空");
        }
        
        if (!StringUtils.hasText(meeting.getBookerName())) {
            throw new RuntimeException("预订人姓名不能为空");
        }
        
        if (meeting.getStartTime() == null) {
            meeting.setStartTime(LocalDateTime.now());
        }
        
        if (meeting.getEndTime() == null) {
            meeting.setEndTime(LocalDateTime.now().plusHours(1));
        }
        
        if (!meeting.getEndTime().isAfter(meeting.getStartTime())) {
            throw new RuntimeException("结束时间必须晚于开始时间");
        }
        
        // 验证会议室是否存在
        MeetingRoom meetingRoom = meetingRoomMapper.findMeetingRoomById(meeting.getRoomId());
        if (meetingRoom == null) {
            throw new RuntimeException("指定的会议室不存在");
        }
        
        // 设置会议室名称（确保与数据库中的一致）
        meeting.setRoomName(meetingRoom.getRoomName());
        
        // 设置默认取消标志为0（未取消）
        if (meeting.getCancelFlag() == null) {
            meeting.setCancelFlag(0);
        }
        
        // 检查会议室是否已被预定
        int conflictCount = meetingMapper.checkBookingConflict(
                meeting.getRoomId(), 
                meeting.getStartTime(), 
                meeting.getEndTime());
        if (conflictCount > 0) {
            throw new RuntimeException("会议室在该时间段已被预定，请选择其他时间或会议室。");
        }
        
        // 保存到数据库
        meetingMapper.insertMeeting(meeting);
        // 返回保存后的会议信息
        return meeting;
    }

    /**
     *
     * @param id 会议ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBooking(int id) {
        return meetingMapper.deleteBooking(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBooking(Meeting meeting) {
        if (meeting == null || meeting.getId() == null) {
            throw new RuntimeException("会议信息或ID不能为空");
        }
        meetingMapper.updateBooking(meeting);
    }

    @Override
    public Meeting findBookingByCondition(String bookerName, String roomName, LocalDateTime startDate, LocalDateTime endDate) {
        return meetingMapper.findBookingByCondition(bookerName, roomName, startDate, endDate);
    }
    
    @Override
    public List<RoomStatusDTO> getRoomStatusByTime(LocalDateTime startTime, LocalDateTime endTime) {
        // 获取所有会议室
        List<MeetingRoom> allRooms = meetingRoomMapper.findAllMeetingRooms();
        
        // 查询结果列表
        List<RoomStatusDTO> roomStatusList = new ArrayList<>();
        
        // 遍历所有会议室
        for (MeetingRoom room : allRooms) {
            RoomStatusDTO roomStatus = new RoomStatusDTO();
            roomStatus.setRoomId(room.getRoomId());
            roomStatus.setRoomName(room.getRoomName());
            roomStatus.setFacilities(room.getFacilities());
            
            // 查询该会议室在指定时间段内的会议
            List<Meeting> meetings = meetingMapper.findMeetingsInRoomAndTimeRange(
                    room.getRoomId(), startTime, endTime);
            
            // 过滤掉已取消的会议
            List<Meeting> activeMeetings = meetings.stream()
                    .filter(meeting -> meeting.getCancelFlag() == 0)
                    .collect(Collectors.toList());
            
            if (activeMeetings.isEmpty()) {
                // 空闲会议室
                roomStatus.setStatus("free");
                roomStatus.setCurrentMeetings(new ArrayList<>());
            } else {
                // 占用会议室
                roomStatus.setStatus("occupied");
                
                // 转换会议信息
                List<RoomStatusDTO.MeetingInfo> meetingInfos = activeMeetings.stream().map(meeting -> {
                    RoomStatusDTO.MeetingInfo info = new RoomStatusDTO.MeetingInfo();
                    info.setId(meeting.getId());
                    info.setBookerName(meeting.getBookerName());
                    info.setMeetingTopic(meeting.getMeetingTopic());
                    info.setStartTime(meeting.getStartTime());
                    info.setEndTime(meeting.getEndTime());
                    return info;
                }).collect(Collectors.toList());
                
                roomStatus.setCurrentMeetings(meetingInfos);
            }
            
            roomStatusList.add(roomStatus);
        }
        
        return roomStatusList;
    }
}